<template>
  <div class="bonus" v-loading="fullscreenLoading">
    <div class="sub-title flex-l-r">
      <div class="content"><span>奖金项：{{parentData.bonusItemName}}</span><span>方案名称：{{parentData.computeName}}</span></div>
    </div>
    <div class="search-form flex-l-r flex-start">
      <div style="width: calc(100% - 350px)">
        <el-radio-group v-model="activeIndex" size="small" @input="handleClick">
          <el-radio-button   :label="item.id" :value="item.id" v-for="item in tabPanels" :key="item.id">{{item.label}}</el-radio-button>
        </el-radio-group>
      </div>
      <div>
        <el-button type="primary" plain @click="divideAgain" v-if="tabPanels.length == activeIndex && programmeItem.status == '已测算'">再次分配</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button type="primary" @click="goBack" plain>返回</el-button>
      </div>
    </div>
    <div class="search-form flex-l-r">
        <div class="l-box">
            <div class="item">
              <span class="txt-bold">可发金额:</span><span class="txt-amount">{{programmeItem.availableAmount}}</span>
            </div>
            <div class="item">
              <span class="txt-bold">剩余金额:</span><span class="txt-amount">{{!programmeItem.remainingAmount ? '0' : programmeItem.remainingAmount}}</span>
            </div>
            <div class="item">
              <el-checkbox class="mg-r10" v-model="checked"><span  class="txt-bold">奖金池:</span><span class="txt-amount">{{programmeItem.poolAmount}}</span></el-checkbox>
            </div>
            <div class="item">
              <span class="txt-bold">公式:</span>
              <el-tooltip class="item" effect="dark" :content="programmeItem.formula" placement="top-start" v-if="programmeItem.formula">
                <span  class="txt-amount long">{{programmeItem.formula}}</span>
              </el-tooltip>
              <span v-else class="txt-amount long">无</span>
            </div>
        </div>
        <div>
          <el-button type="success" @click="selectOrg" plain>选择机构</el-button>
          <el-button type="success" @click="selectFormula" plain>选择公式</el-button>
          <el-button type="success" @click="changeValueOfColumn" plain>批量调整</el-button>
          <el-button type="primary" @click="countHandle" plain :disabled="formData.tableData.length == 0 || !programmeItem.formula">计算</el-button>
        </div>
    </div>
    <div>
      <el-form :model="formData" ref="formDataRef">
         <el-table ref='tableRef' class="edit-table"
                   :data="formData.tableData" v-loading="loading" border
                   @selection-change="handleSelectionChange"
                   :height="`calc(100vh - 260px )`">
              <el-table-column
                width="60px"
                prop=""
                label="序号"
                fixed
                align="center"
              >
                <template slot-scope="scope">
                  {{(page.currentPage - 1) * page.pageSize + scope.$index + 1}}
                </template>
              </el-table-column>
              <el-table-column
                prop="deptName"
                label="机构名称"
                align="left"
                width="300"
                fixed
                show-overflow-tooltip
              ></el-table-column>

              <el-table-column
                v-for="(item,index) in columns"
                :prop="item.prop"
                :label="item.label"
                :key="index"
                align="center"
                v-if="item.children.length != 0"
              >
                <template slot="header" slot-scope="scope">
                  <span>{{item.label}}</span>
                  <el-tooltip class="item" effect="dark" content="与下发通知单位核对单位人数、考核金额" placement="top" v-if="index==0">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </template>
                <el-table-column v-for="(_item,_index) in item.children" :label="_item.label" :prop="_item.prop" :key="_item.prop" align="center" header-align="center" min-width="120">
                  <template v-slot="scope" >
                    <el-form-item :prop="`tableData.${scope.$index}.${_item.prop}`"  :rules="[{validator:$validateUtil.dynamic,prop:_item.prop,label:_item.label,row:scope.row,ruleType:'',trigger: 'change' }]">
                      <el-input-number  :controls="false" v-model.trim="scope.row[_item.prop]" placeholder="请输入"
                                        @change="saveCell(scope.row,_item.prop,`${scope.$index}`)" ></el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
             </el-table-column>
           </el-table>
      </el-form>
    </div>
    <!--选择机构-->
    <select-org-or-group-form ref="selectOrgOrGroupFormRef" @sendOrgGroupData="getOrgGroupData" :loading="orgGropLoading"></select-org-or-group-form>
    <!--选择公式 -->
    <select-formula-com ref="selectFormulaComRef" @sendFormulaInfo="getFormulaInfo" :loading="formulaLoading"></select-formula-com>
    <!-- 批量修改值 -->
    <modify-batch-value-com ref="modifyBatchValueComRef" @refresh="refresh"></modify-batch-value-com>
  </div>
</template>

<script>
import selectOrgOrGroupForm from "@/views/bonusmanage/calculate/org/programme/selectOrgOrGroupForm";
import selectFormulaCom from "@/views/bonusmanage/components/selectFormulaCom";
import modifyBatchValueCom from "@/views/bonusmanage/components/modifyBatchValueCom";
import {
  getProgrammeId,
  addOrgOrGroup,
  saveFormula,
  measureOrgList,
  saveCell,
  compute,
  getViewColumn, submitToProcess
} from '@/api/bonus/calculateorgprogramme'

export default{
  name:"measurement",
  components:{
    selectOrgOrGroupForm,
    selectFormulaCom,
    modifyBatchValueCom
  },
  data() {
    return {
      show:true ,
      fullscreenLoading:false,
      orgGropLoading:false,
      formulaLoading:false,
      loading:false,

      page:{
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      tableData: [],
      formData:{tableData:[]},
      filteredData:[],
      checked:false,
      searchForm: {},
      multipleSelection: [],
      ids:[],
      programmeItem:{},
      parentData:{} ,
      columns:[
        {
          label: '通知单下发额度',
          prop: 'configItem',
          minWidth:140,
          children: [
          ]
        },
        {
          label: '奖励明细',
          prop: 'reward',
          children:[]
        },
        {
          label: '惩罚明细',
          prop: 'penalty',
          children:[]
        }
      ],
      //tab相关
      tabPanels:[ //默认显示第一次
        // {
        //   label:'第1次分配',
        //   id:"1"
        // },
      ],
      activeIndex:'1',
      tabIndex:0,
      currentTab:'1',
      initTriggerNum:1 //记录init被执行的次数
    }
  },
  computed: {

  },
  created(){

  },
  methods:{
    init(data){
      this.parentData = data ;
      if (this.initTriggerNum == 1){//从列表页进来，init第一次执行，此时执行以下代码；在本页面再调用init时，都不需要执行下面的方法
        this.getTabPanels(data.computeCount || 1) ;
      }
      this.initTriggerNum ++ ;

      this.fullscreenLoading = true ;
      //获取奖金金额以及方案的id,从列表页进来默认加载第1次分配数据
      this.handleClick(this.activeIndex,this.parentData.bonusCount) ;
    },

    /**
     * @param divideCount 一共分配了几次
     * 根据分配次数组装tab结构 => eg: 2 => [{label:'第1次分配',id:'1'},{label:'第2次分配',id:'2'}]
     * */
    getTabPanels(divideCount){
      for (let i = 0 ; i < divideCount ; i++){
        this.tabPanels.push({  label:'第'+( i + 1) + '次分配', id: (i+1).toString()})
      }
    },
    //切换tab 触发handleClick有两种情：1.从列表页进来，执行init方法时，此时需要传bonusCount(可分配金额)；2.切换tab的时候，此时不需要传bonusCount
    handleClick(tab,bonusCount){
      this.currentTab = tab ;
      this.getProgrammeId(tab,bonusCount) ;
    },
    /**
     * @param computeNo 第几次分配的索引值 eg:1 第一次分配 2 第二次分配 ....
     * @param bonusCount  可分配的奖金金额（不传值时是查询）
     * */
    getProgrammeId(computeNo,bonusCount){
      this.parentData.computeDeptId = this.parentData.id ;
      this.parentData.computeNo = computeNo //第几次的分配
      this.parentData.availableAmount = bonusCount //可分配的奖金金额
      getProgrammeId(this.parentData).then(res=>{
          if (res.data.code == 0){
            this.programmeItem = res.data.data //后台返回的方案信息

            //获取动态列(在列表页面通过【配置】而来)
            this.getDynamicColumnsOne(this.parentData) ;

            //获取要测算的机构数据
            this.getOrgList(this.programmeItem) ;
          }

      }).catch(err=>{

      })
    },
    //再次分配
    divideAgain(){
      let addTabIndex = this.tabPanels.length + 1
      this.activeIndex = addTabIndex.toString()  ;
      this.tabPanels.push({label: '第'+ addTabIndex + '次分配',id: addTabIndex.toString()})
      this.getProgrammeId(this.tabPanels.length,this.programmeItem.remainingAmount) ;//将本次的剩余金额做为可发金额
    },
    //获取动态列(与列表页【配置】中选中的列有关，选几项，展示对应选中项的列)
    getDynamicColumnsOne(parentData){
      getViewColumn(parentData.id).then(res=>{
        if (res.data.code == 0){

            res.data.data.map(item=>{
              item.prop = item.value
            })
            this.columns[0].children = res.data.data ;

            //获取动态列(奖惩)
            this.getDynamicColumnsTwo(this.programmeItem) ;

            this.$nextTick(()=>{
              this.$refs.tableRef.doLayout() ;
            })
        }
      }).catch(err=>{

      })
    },
    //获取动态列(奖、惩)
    getDynamicColumnsTwo(programmeItem){
      //奖列
      if (programmeItem.reward){
        this.columnsFormat(1,programmeItem.reward)
      }
      //惩列
      if (programmeItem.penalty){
        this.columnsFormat(2,programmeItem.penalty)
      }
    },
    columnsFormat(index,propStr){
      this.columns[index].children = propStr.substring(0,propStr.length - 1).split(',').map(item=>{
        return {prop:item,label: item}
      })
    },
    //获取测算机构、虚拟组列表
    getOrgList(programmeItem){
      if (!programmeItem) return
      measureOrgList({computeSubId:programmeItem.id}).then(res=>{
         if (res.data.code == 0){
            this.formData.tableData = this.tableFormat(res.data.data,['otherReward','otherPenalty'])//res.data.data
            this.oldTableData = JSON.parse(JSON.stringify(this.formData.tableData)) ;//单元格编辑失败时，恢复原始值
            this.$refs.tableRef.doLayout() ;
         }
         this.fullscreenLoading = false ;
      }).catch(err=>{
        this.fullscreenLoading = false ;
      })
    },
    //在返回的数据中，关于动态列的数据放到了一个字段里为json格式，将其展开转成对象 eg:[...,{reward:'{优秀奖:2000,优秀个人:3000}',detpName:'业务部'},{}]  ==》 [...,{reward:'{优秀奖:2000,优秀个人:3000}',detpName:'业务部',优秀奖:2000,优秀个人:3000},{}]
    tableFormat(tableData,needTransFormProp){
       tableData.map(item => {
         for (let key in item){
           if (needTransFormProp.includes(key)){
             let dynimicCol = JSON.parse(item[key])
             if (dynimicCol){
               for (let key in dynimicCol){
                 item[key] = dynimicCol[key]
               }
             }
           }
         }
       })
      return tableData ;
    },
    handleSelectionChange(list){
      this.multipleSelection = list ;
      this.ids = this.multipleSelection.map((ele) => {
        return ele.id
      })
    },
    submit(){
     this.$refs.formDataRef.validate(validate=>{
         if (validate){
           this.$confirm('提交工作流后不可修改，确定要提交吗', '提示', {
             confirmButtonText: '确定',
             cancelButtonText: '取消',
             type: 'warning'
           }).then(() => {
             this.loading = true ;
             submitToProcess(this.programmeItem.id).then(res=>{
               if (res.data.code == 0){
                 this.$message.success('操作成功')
                 this.goBack()
               }
               this.loading = false ;
             }).finally(()=>{
               this.loading = false ;
             })
           }).catch(() => {

           });
         }
      })
    },
    //选择机构，然后弹出框
    selectOrg(){
      let type = ''
      if (this.formData.tableData.length == 0 || (this.formData.tableData.length > 0 && this.formData.tableData[0].deptType == 'JG')){
        type = 'org' //机构
      }else{
        type = 'groupTab' //分组
      }
      this.$refs.selectOrgOrGroupFormRef.init(this.formData.tableData,type) ;
    },
    //选择公式，然后弹出框
    selectFormula(){
      this.$refs.selectFormulaComRef.init('jg',{gsId:this.programmeItem.formulaId,gsMc:this.programmeItem.formula}) ; //回显
    },
    //批量修改某列的值，然后弹出框
    changeValueOfColumn(){
       this.$refs.modifyBatchValueComRef.init('jg',this.programmeItem.id) ;
    },
    //机构|虚拟分组弹出框后，点确定执行该方法
    getOrgGroupData(list,type){
      if (type == 'org'){ //机构
        this.deptType = 'JG'
        this.ids = list.map(item=>{
           return item.bonusDeptId ;
        })
      }else{ //虚拟组
        this.deptType = 'FZ'
        this.ids = list.map(item=>{
          return item.id ;
        })
      }
      this.addOrgOrGroup() ;
    },
    addOrgOrGroup(){
      this.orgGropLoading = true ;
      addOrgOrGroup({ids:this.ids.toString(),deptType:this.deptType,computeSubId:this.programmeItem.id}).then(res=>{
        if (res.data.code == 0){
          this.$refs.selectOrgOrGroupFormRef.handleCancel() ;//关闭对话框
          this.init(this.parentData) //重新刷新界面
        }
        this.orgGropLoading = false ;
      }).catch(err=>{
        this.orgGropLoading = false ;
      })
    },
    refresh(){
      this.init(this.parentData) ; //重新刷新界面
    },
    //从弹出框中选择的公式后，返回到此页面，并赋值
    getFormulaInfo(formulaInfo){
      this.programmeItem.formula = formulaInfo.gsMc //公式名称
      this.programmeItem.formulaId = formulaInfo.gsId //公式id
      //保存公式
      this.saveFormula(this.programmeItem) ;
    },
    saveFormula(programmeItem){
       this.formulaLoading = true ;
       saveFormula(programmeItem.id ,programmeItem.formulaId).then(res=>{
           if (res.data.code == 0){
             this.$refs.selectFormulaComRef.handleCancel() ; //保存成功后，关闭公式弹框
           }
         this.formulaLoading = false ;
       }).catch(err=>{
         this.formulaLoading = false ;
       })
    },
    /**
     *
     * @param rowData 点击的单元格所在行的数据
     * @param prop  点击的单元格的属性
     * @param index 点击的单元格的行索引 从 0 开始
     */
    saveCell(rowData,prop,index){
      let flag = true ;
      this.$refs.formDataRef.validateField(`tableData.${index}.${prop}`,valid => { //被点击的单元格的验证
        if (!valid){
          flag = true ;
        }else{
          flag = false ;
        }
      });

      if (!flag) return
      this.loading = true
      saveCell({id:rowData.id,columnName:prop,columnValue:rowData[prop]}).then(res=>{
        if (res.data.code == 0){
          this.$message.success('修改成功')
        }else{
          this.$message.error('修改失败')
          this.formData.tableData[index][prop] = this.oldTableData[index][prop] //如果保存失败，恢复到初始值
        }
        this.loading = false
      }).catch(err=>{
        this.formData.tableData[index][prop] = this.oldTableData[index][prop] //如果保存失败，恢复到初始值
        this.loading = false
      })
    },

    //计算
    countHandle(){
      this.fullscreenLoading = true ;
      compute({computeSubId:this.programmeItem.id}).then(res=>{
        if (res.data.code == 0){
          this.init(this.parentData) //重新刷新界面
        }
        this.fullscreenLoading = false ;
      }).catch(err=>{
        this.fullscreenLoading = false ;
      })
    },
    goBack(){
      this.tabIndex = 0
      this.initTriggerNum = 0
      this.$emit('close',true)
    },
  }
}
</script>
<style scoped>

</style>
